package com.xiong.wuliao.homeweather;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Author : xiong.
 * Time : 2017/2/15.
 */
public class NetWorkUtils {
	public static String doGet(String uri) {
		// 创建缓存字符串对象
		StringBuffer sBuffer = new StringBuffer();
		String result = null;
		try {
			URL url = new URL(uri);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(10 * 1000);// 设置链接超时时间
			connection.setReadTimeout(10 * 1000);// 设置读取输入流超时时间10秒
			InputStream iStream = connection.getInputStream();
			BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));

			// 读取数据
			String line = bReader.readLine();
			while (line != null) {
				sBuffer.append(line);
				line = bReader.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result = sBuffer.toString();
		if (result.contains("weather_callback")) {
			result = result.substring(result.indexOf("(") + 1, result.lastIndexOf(")"));
		}
		return result;
	}

	// 检测网络状态，返回true 表示有网络，返回false 表示没有网络
	public static boolean isActive(Context context) {
		boolean flag = false;
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info != null) {
			flag = info.isAvailable();
		}
		return flag;
	}

}
